package cn.dglydrpy.study.j2ee.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
 * 通过实现Servlet接口来写servlet 可重写生命周期函数 其他同继承HttpServlet一样
 */
public class HelloServlet implements Servlet {

	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public ServletConfig getServletConfig() {
		// TODO Auto-generated method stub
		return null;
	}

	public String getServletInfo() {
		// TODO Auto-generated method stub
		return null;
	}

	public void init(ServletConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
		// 由于getMethod方法是HttpServletRequest对象的方法,所以需要强制转型才能调用
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res= (HttpServletResponse)response;
		// 获取请求行中的请求方式(GET/POST)
		String method = req.getMethod();
		// 获取请求行中的 URI
		String uri = req.getRequestURI();
		// 获取请求行中的HTTP版本
		String http = req.getProtocol();
		System.out.println(method + " " + uri + " " + http);

		// 获取请求头中的信息
		String host = req.getHeader("Host");
		String ua = req.getHeader("User-Agent");

		System.out.println(host);
		System.out.println(ua);
		// 获取全部的请求头信息:
		// Enumeration 与 Iterator 功能相同
		Enumeration<String> em = req.getHeaderNames();
		// em.hasMoreElements() 与 it.hasNext() 相同
		// em.nextElement(); 与 it.next() 相同
		while (em.hasMoreElements()) {
			String name = em.nextElement();
			System.out.println(name + ":" + req.getHeader(name));
		}

		//利用response对象, 处理对用户浏览器的响应
		//设置响应状态码, 默认状态码就是200
		res.setStatus(200); //400 500 302 等
		//设置响应头, 设置UTF-8支持中文
		res.setContentType("text/html;charset=utf-8");
		//3 获取 PrintWriter对象, 字符流, 封装字符的编码功能. 按照ContentType设置编码utf-8
		PrintWriter out = res.getWriter();
		//PrintWriter 会自动处理文字编码,设置ContentLength
		String str = "<html><body><h1>"
				+ "今天天气不错!"
				+ "</h1></body></html>";
		byte[] bytes = str.getBytes("utf-8");
		//设置消息正文长度
		res.setContentLength(bytes.length); 
		//添加一个自定义的响应头
		res.setHeader("msg", "Hello World!"); 
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
		out.println("<h1>hello,servlet!</h1>");
		out.println("<h1>"+sdf.format(new Date())+"</h1>");
		
		//发送消息正文  使用字节流
		res.getOutputStream().write(bytes); 
		//将response中的信息刷出, 反馈到浏览器
		//如果不调用这个方法, Tomcat会自动调用!
		res.flushBuffer();
	}

}
